<template>
  <div id="music" class="music" @click="toggleMusic">
    <div class="cloud">
      <div class="note" :class="isPlay ? 'rotating on' : 'off'"></div>
    </div>
    <audio :src="musicURL" id="myMusic" preload="preload" loop></audio>
  </div>
</template>

<script>
export default {
  name: 'MusicPlayer',
  data () {
    return {
      musicURL: require('./../assets/gbqq.mp3'),
      isPlay: true
    }
  },
  mounted () {
    this.audioPlay()
    document.addEventListener('touchstart', this.audioPlay)
  },
  methods: {
    toggleMusic () {
      if (this.isPlay) {
        this.audioPause()
      } else {
        this.audioPlay()
      }
      this.isPlay = !this.isPlay
    },
    audioPlay () {
      document.removeEventListener('touchstart', this.audioPlay)
      const audio = document.getElementById('myMusic')
      audio.play()
      document.addEventListener('WeixinJSBridgeReady', function () {
        audio.play()
      }, false)
    },
    audioPause () {
      const audio = document.getElementById('myMusic')
      audio.pause()
      document.addEventListener('WeixinJSBridgeReady', function () {
        audio.pause()
      }, false)
    }
  }
}
</script>

<style lang="less" scoped>
.music {
  position: absolute;
  right: 50px;
  top: 50px;
  z-index: 99;
  width: 80px;
  height: 80px;
  .cloud {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 80px;
    .note {
      width: 80px;
      height: 80px;
      background-size: cover;
      background-repeat: no-repeat;
    }
    .on {
      background-image: url('./../assets/img/play.png');
    }
    .off {
      background-image: url('./../assets/img/pause.png');
    }
    .rotating {
      animation: rotate-music 2s linear infinite;
    }
  }
  @keyframes rotate-music {
    0% {
      transform: rotate(0);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}
</style>
